<!--
* description: 内部领用单编辑
* author: hezm
* createdDate: 2021-1-25
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="biaoName"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
      @open="open"
    >
      <dialogHeader
        slot="title"
        :title="biaoName"
        :style-type="$store.state.app.dialogType"
      />
      <one-table-template
        ref="multipleTable"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-api-config="apiConfig"
        :dynamic-table-cols="tableCols"
        :dynamic-form-fields="formField"
        :num-list="numList"
        :dynamic-table-defult-height="400"
        :dynamic-is-show-select="true"
        :callback-obj="callbackObj"
        :dynamic-api-style="'restful'"
      >
        <template #qty="scope">
          <el-input
            v-model="scope.row['qty']"
            placeholder="输入领用数量"
            @input="numChange($event, scope.row, scope.col)"
          />
        </template>
      </one-table-template>
    </el-dialog>
    <!--    <edit-->
    <!--      :dynamic-edit-row-data="editRowData"-->
    <!--      :popups-visible-time="popupsVisibleTime"-->
    <!--      :dynamic-api-style="'restful'"-->
    <!--      :ware-id="wareId"-->
    <!--      :list="list"-->
    <!--      @list="upSon($event)"-->
    <!--      @close="close"-->
    <!--    />-->
    <!-- 备件选择 -->
    <part-select
      :is-view-part.sync="isViewPart"
      :row-data="rowData"
      :close-disabled="true"
      :chosen-list.sync="chosenList"
      :cur-select-list.sync="curSelectList"
      :custom="custom"
      @selectiondataPart="selectiondata2"
    />
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
// import { formMixins } from '@/components/mixins/formMixins'
import { orgApis } from '@/api/paSparePartsManagement'
import OneTableTemplate from '@/components/templates/oneTable'
import PartSelect from '@/views/pa/purchasingManagement/partOrderBranchMake/partSelectNew.vue'
// import request from '@/utils/request'
export default {
  components: {
    OneTableTemplate,
    dialogHeader: () => import('@/components/dialogHeader'),
    // mixButton: () => import('@/components/basicComponent/mixButton'),
    // Edit: () => import('./edit')
    PartSelect
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    numList: { type: String, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },

  data() {
    const viewPageCode = 'bigAreaInfo-edit'
    return {
      isViewPart: false,
      rowData: {},
      chosenList: [],
      curSelectList: [],
      uploadPath: '',
      list: [],
      wareId: '',
      biaoName: '内部领用单编辑',
      numList: 2,
      hideSet: true,
      getArray: [],
      editRowData: {},
      deteleArray: [],
      popupsVisibleTime: false,
      apiConfig: orgApis.queryStorage,
      custom: {
        api: {
          APIUrl: '/mp/e3sh/spareparts/requisitionFormProductionService/queryAccessoriesSelection.do'
        },
        tableComponents: [
          {
            compKey: 'compKey1',
            labelName: '备件编码：',
            codeField: 'partNo',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey2',
            labelName: '备件名称：',
            codeField: 'partName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey4',
            labelName: '维修类别：',
            codeField: 'partRepairType',
            component: () => import('@/components/org/commonSelect'),
            type: 'dropdownList',
            customObj: {
              api: orgApis.dropDownKey
            },
            isMust: true
          },
          {
            compKey: 'compKey5',
            labelName: '销售开关：',
            codeField: 'isSale',
            component: () => import('@/components/org/LookupValue'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '1', statusText: '启用' },
              { statusId: '0', statusText: '停用' }
            ],
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey6',
            labelName: '订货开关：',
            codeField: 'isOrder',
            component: () => import('@/components/org/LookupValue'),
            oFields: 'statusId,statusText',
            options: [
              { statusId: '1', statusText: '启用' },
              { statusId: '0', statusText: '停用' }
            ],
            type: 'dropdownList',
            isMust: true
          },
          {
            compKey: 'compKey7',
            labelName: '供应商：',
            codeField: 'supplierCode',
            component: () =>
              import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey8',
            labelName: '适用车型：',
            codeField: 'carConfigIdList',
            component: () =>
              import('@/components/org/commonInput'),
            type: 'dropdownList',
            isMust: true
          }
        ],
        tableCols: [
          { prop: 'partNo', label: '备件编码', align: 'center' },
          { prop: 'partName', label: '备件名称', align: 'center' },
          { prop: 'partRepairTypeCn', label: '维修类型', align: 'center' },
          { prop: 'carConfigIdList', label: '适用车型', align: 'center', width: 120 },
          { prop: 'referencePrice', label: '参考价格', align: 'center' },
          { prop: 'snp', label: '最小销售包装', align: 'center' },
          { prop: 'isRetrospect', label: '追溯备件', align: 'center' },
          { prop: 'supplierCode', label: '供应商编码', align: 'center' },
          { prop: 'supplierShortName', label: '供应商名称', align: 'center' },
          { prop: 'remark', label: '备注', align: 'center' }
        ],
        formField: {
          partNo: '',
          partName: '',
          partRepairType: '',
          isSale: '',
          isOrder: '',
          supplierCode: '',
          carConfigIdList: '',
          warehouseId: ''
        }
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: '',
          size: 'small',
          icon: '',
          clickEvent: this.opendEdit,
          text: '备件选择',
          position: 'left',
          disabled: false
        },

        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          icon: '',
          clickEvent: () => this.deteleList(),
          text: '备件删除',
          position: 'left'
        },
        {
          compKey: 'btnKey3',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          click: (event) => { this.templateDownload() }
        },
        {
          compKey: 'btnKey4',
          type: '',
          size: 'small',
          text: '批量导入',
          name: 'import',
          customUpload: param => {
            if (!this.formField.warehouseId) {
              return this.$message('请先选择领用仓库!')
            }
            this.$refs['multipleTable'].$refs['mixBtn1'].$refs['upload'][1].clearFiles()
            const that = this
            const url = `/mp/e3sh/spareparts/requisitionFormProductionService/importSpareParts1.do`
            that.$requestUpload(url, param, {
              warehouseId: this.formField.warehouseId
            }).then((response) => {
              if (response.result === '1') {
                response.rows.forEach((element) => {
                  this.$refs.multipleTable.list.push(element)
                })
                this.$message({
                  message: '导入成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: response.msg,
                  type: 'warning'
                })
              }
            })
              .catch((err) => {
                this.$message({
                  message: response.msg,
                  type: 'warning'
                })
              })
          },
          customUploadList(a, b) {
            console.log(a, b)
          },
          customExceed(a) {
            console.log(a)
          },
          position: 'upload'
        },

        {
          compKey: 'btnKey5',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.editSave(),
          disabled: false,
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'btnKey6',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.editReset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey7',
          type: '',
          size: 'small',
          // clickEvent: () => this.handFileListChangePush(),
          name: 'importTemplate',
          position: 'upload',
          text: '附件上传',
          customUpload: (param) => {
            // console.log(param)
            // 清除已上传文件
            this.$refs['multipleTable'].$refs['mixBtn1'].$refs['upload'][1].clearFiles()
            const loading = this.$loading({
              lock: true,
              text: '上传中...',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            const that = this
            const url = '/mp/file/notice/upload.do'
            that
              .$requestUpload(url, param)
              .then((response) => {
                loading.close()
                if (response.result === '1') {
                  this.$message({
                    message: '上传成功',
                    type: 'success'
                  })
                  this.upLoadList = response.path
                  const [name, path] = response.path[0][0].split('|')
                  this.formField.annex = path
                  // that.queryTable();
                } else {
                  this.$message({
                    message: response.msg,
                    type: 'warning'
                  })
                }
              })
              .catch((err) => {})
              .finally(() => {
                loading.close()
              })
          },
          customUploadList(a, b) {
            console.log(a, b)
          },
          customExceed(a) {
            console.log(a)
          }
        }
      ],

      // 动态组件-查询条件
      tableComponents: [
        {
          compKey: 'compKey1',
          labelName: '领用单号：',
          codeField: 'requisitionCode',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: false,
          isMust: true,
          disabled: true
        },
        {
          compKey: 'compKey2',
          labelName: '领用仓库: ',
          codeField: 'warehouseId',
          component: () => import('@/components/org/commonSelect'),
          type: 'dropdownList',
          customObj: {
            api: orgApis.queryCK,
            defOptionFields: ['warehouseId', 'warehouseName']
          },
          // change: this.changeLike,
          isRequire: true,
          isMust: true,
          disabled: this.hideSet
        },
        {
          compKey: 'compKey3',
          labelName: '领用部门：',
          codeField: 'deptName',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: false,
          disabled: true,
          isMust: true
        },

        {
          compKey: 'compKey4',
          labelName: '领用人: ',
          codeField: 'empName',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isRequire: false,
          isMust: true
        },

        {
          compKey: 'compKey5',
          labelName: '领用用途：',
          codeField: 'requisitionUse',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true
        },

        {
          compKey: 'compKey6',
          labelName: '收货人：',
          codeField: 'receiver',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true
        },

        {
          compKey: 'compKey7',
          labelName: '联系电话：',
          codeField: 'receiverPhone',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          validrule: {
            isPhone: true,
            maxlength: 11
          },
          isMust: true,
          isRequire: true
        },

        {
          compKey: 'compKey8',
          labelName: '收货地址：',
          codeField: 'receiverAddress',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true
        },

        {
          compKey: 'compKey9',
          labelName: '预算号:',
          codeField: 'budgetNumber',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          isRequire: true
        },
        // {
        //   compKey: 'compKey10',
        //   labelName: '运输方式：',
        //   codeField: 'transportModeId',
        //   textField: 'transportModeName',
        //   component: () => import('@/components/org/commonSelect'),
        //   customObj: {
        //     api: { ServiceCode: 'queryPartTransports', APIUrl: '/mp/e3sh/spareparts/mallorder/partSaleOrderQueryOemService/queryPartTransports.do' }
        //   },
        //   oFields: 'transportModeId,transportModeName',
        //   type: 'dropdownList',
        //   isMul: false,
        //   isMust: true,
        //   isRequire: true,
        //   span: 6
        // }
        // {
        //   compKey: "compKey11",
        //   labelName: "附件上传：",
        //   codeField: "annex",
        //   component: () => import("@/components/org/commonInput"),
        //   type: "inputText",
        //   isMust: true,
        //   isRequire: false,
        //   span: 12,
        // },
      ],

      tableCols: [
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlId',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'partNo',
          label: '备件编码',
          hidden: false
          //   alwaysHidden: true
        },
        {
          prop: 'partName',
          label: '备件名称'
        },
        {
          prop: 'number',
          label: '库存数量'
        },
        {
          prop: 'qty',
          label: '领用数量',
          isShowLabel: false,
          isSlot: true
          // isComponent: true,
          // comps: [
          //   {
          //     compKey: 'qty',
          //     codeField: 'qty',
          //     component: () => import('@/components/org/commonInput'),
          //     isRequire: true,
          //     span: 23,
          //     validrule: { min: '1', noRequire: true }
          //   }
          // ]
        }
      ],

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          requisitionId: '',
          requisitionCode: '',
          deptName: '',
          empName: '',
          requisitionUse: '',
          receiver: '',
          receiverPhone: '',
          receiverAddress: '',
          budgetNumber: '',
          annex: '',
          warehouseId: '',
          transportModeId: '',
          transportModeName: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      callbackObj: {
        // 手动勾选网格时，拿到勾选网格的数据
        onCheckSelect: (selection, row) => {
          this.deteleArray = selection
        },
        onCheckSelectAll: (selection) => {
          this.deteleArray = selection
        }
      }
    }
  },
  watch: {
    curPopupsVisible(val, old) {
      if (val) {
        this.biaoName = '内部领用单编辑'
        if (this.numList == 'edit') {
          for (const key in this.formField) {
            this.formField[key] = this.dynamicEditRowData[key]
          }
          this.tableButtons.forEach((item, index) => {
            item.disabled = false
          })
          this.$nextTick(() => {
            this.queryTable(1)
          })
          // this.formField ={...this.dynamicEditRowData}
          // console.log( this.formField)
        } else if (this.numList == 'eye') {
          this.biaoName = '内部领用单查看'
          this.tableButtons.forEach((item, index) => {
            item.disabled = true
          })
          for (const key in this.formField) {
            this.formField[key] = this.dynamicEditRowData[key]
          }
          this.$nextTick(() => {
            this.queryTable(1)
          })
        } else {
          this.biaoName = '内部领用单新增'
          this.tableButtons.forEach((item, index) => {
            item.disabled = false
          })
        }
      }
    }
  },
  mounted() {
    // this.open()
  },
  methods: {
    // 重置
    editReset() {
      if (this.numList === 'edit') {
        for (const key in this.formField) {
          this.formField[key] = this.dynamicEditRowData[key]
        }
      } else {
        this.reset()
      }
    },
    numChange(val, row, col) {
      const panter = /c|(^[1-9][0-9]*$)/
      if (!panter.test(val)) {
        row[col['prop']] = val.slice(0, -1)
        if (val) { return this.$message('请输入正确的领用数量！') }
      }
      if (Number(val) > Number(row['number'])) {
        row[col['prop']] = val.slice(0, -1)
        return this.$message('领用数量应小于库存数量!')
      }
    },
    // changeLike() {
    //   this.queryTable(1)
    // },
    // upSon(base) {
    //   base.forEach(item => {this.$set(item, 'qty', '')})
    //   this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.concat(base)
    // },
    selectiondata2(selection) {
      selection.forEach(item => { this.$set(item, 'qty', '') })
      this.$refs['multipleTable'].list = selection
    },
    closeEdit() {
      this.curPopupsVisible = false
      this.popupsVisibleTime = false
      this.$refs['multipleTable'].list = []
      this.$emit('close', false)
    },
    opendEdit() {
      if (!this.formField.warehouseId) return this.$message('请先选择领用仓库!')
      // this.wareId = this.formField.warehouseId
      // this.list = this.$refs['multipleTable'].list
      // this.popupsVisibleTime = true
      this.custom.formField.warehouseId = this.formField.warehouseId
      this.rowData = { }
      this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
      const lis = this.$utils.deepCopy(this.$refs['multipleTable'].list)
      lis.forEach(o => o['cur'] = true)
      this.curSelectList = lis
      this.isViewPart = true
    },
    deteleList() {
      for (const i of this.deteleArray) {
        this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.filter((item) => item !== i)
      }
    },
    close(type) {
      this.popupsVisibleTime = type
    },
    editSave() {
      this.$utils.validataMoth(this,
        'validpage',
        undefined, '',
        ''
      )
      if (!this.valid) return
      const that = this
      const infoList = this.formField
      infoList.list = this.$refs['multipleTable'].list
      var isNUm = infoList.list.every(item => {
        return /(^[1-9]\d*$)/.test(item.qty)
      })
      if (!isNUm) {
        that.$message({
          message: '领用数量需为大于零的正整数',
          type: 'warning',
          duration: 2000
        })
        return
      }
      const queryObj = {
        apiConfig: orgApis.insertRequisition,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: infoList
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '0') {
          that.$message({
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          return
        }
        var getResult = response
        if (getResult.result === '1') {
          that.$message({
            message: getResult.msg,
            type: 'success',
            duration: 2000
          })
          this.curPopupsVisible = false
          that.$parent.queryTable(1)
        } else {
          that.$message({
            message: getResult.msg,
            type: 'warning',
            duration: 2000
          })
        }
      })
    },
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('内部领用单制作模板.xlsx')
      this.$requestAPI({
        apiUrl: orgApis.downSpareParts.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },
    handleExceed() {

    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能上传后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    // 批量导入
    handFileListChange(file, fileList) {
      this.handleChange(file)
    },
    handleChange(param, key) {
      // param.warehouseId = this.formField.warehouseId
      // console.log(param,'param')
      const that = this
      const url = `/mp/e3sh/spareparts/requisitionFormProductionService/importSpareParts1.do`
      that.$requestUpload(url, param, {
        warehouseId: this.formField.warehouseId
      }).then((response) => {
        if (response.result === '1') {
          response.rows.forEach((element) => {
            this.$refs.multipleTable.list.push(element)
          })
          this.$message({
            message: '导入成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        }
      })
        .catch((err) => {
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        })
    },

    // 上传附件
    // handFileListChangePush(param) {
    //   const that = this;
    //   const url = "/mp/file/commonUpload/upload.do";
    //   that
    //     .$requestUpload(url, param)
    //     .then((response) => {
    //       if (response.result === "1") {
    //         //  路径
    //         let attachmentFilePath = response.path[0][0].split("|")[1];
    //         // 文件名
    //         let fileName = response.path[0][0].split("|")[0];
    //         let dataParmas = { fileName, attachmentFilePath };
    //         that.addFilePath(dataParmas);
    //       }
    //     })
    //     .catch((err) => {});
    // },
    // 上传附件
    // addFilePath(dataParmas) {
    //   dataParmas.claimID = this.formField.claimID;
    //   request({
    //     url: api.addFilePath.APIUrl,
    //     method: "post",
    //     data: dataParmas,
    //   }).then((res) => {
    //     if (res.result == "1") {
    //       this.$message.success("上传附件成功")
    //     }
    //   });
    // },
    open() {
      this.$nextTick(() => {
        if (this.numList == 'edit' || this.numList == 'eye') {
          this.queryTable(1)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan {
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

